﻿Imports Microsoft.VisualBasic
Imports System.IO

Module ModuleUpdate
    Public app As CApplicationManager = CApplicationManager.GetInstance()

    'Public Const DownloadFile = "../common/pda/Release.zip"
    Public Const DownloadFile = "common/pda/Release.zip"
    Public Const tmpFileName = "master\Release.zip"
    Public Const tmpPath = "master\software"

    Public Sub Main(ByVal args() As String)
        Dim pid As Integer
        Try
            If args.Length >= 1 Then
                pid = CInt(args(0))
                Dim p As Process = CApplicationManager.GetProcess(pid)
                p.Kill()
            End If
        Catch ex As Exception
            MsgBox("三点照合の起動が確認できません。")
        End Try

        Dim frm As FormUpdate = New FormUpdate()
        frm.ShowDialog()
    End Sub


    Public Function fileDownload(ByVal pathFileName As String) As Boolean
        '' ---------------------------------------------------------------------
        '' 設定情報
        Dim AppManager As CApplicationManager = CApplicationManager.GetInstance
        Dim urlAdd As String = AppManager.GetAppSettings.ServerAddress
        Dim userId As String = AppManager.GetAppSettings.UserId
        Dim Password As String = AppManager.GetAppSettings.UserPassword

        'フォルダがない場合
        If Not System.IO.Directory.Exists(Path.GetDirectoryName(pathFileName)) Then
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(pathFileName))
        End If

        Dim copyFilePath As String = Nothing
        Try
            Dim postData As String = Nothing
            copyFilePath = CApplicationManager.GetRealPath(tmpFileName, CApplicationManager.EnumSpecialFolder.PATH_MYDOCUMENT)

            '既存のファイルがあるかないか判断
            If File.Exists(pathFileName) Then
                '' ファイルが存在していた場合は削除
                File.Delete(pathFileName)
            End If
            'MessageBox.Show("urlAdd & DownloadFile:" & vbNewLine & urlAdd & DownloadFile)
            'WebRequestの作成
            Dim webreq As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(urlAdd & DownloadFile), System.Net.HttpWebRequest)
            webreq.Credentials = New System.Net.NetworkCredential(userId, Password)

            Dim res As System.Net.HttpWebResponse = CType(webreq.GetResponse(), System.Net.HttpWebResponse)

            '応答データを受信するためのStreamを取得
            Dim resStream As System.IO.Stream = res.GetResponseStream()

            Try
                If Not System.IO.Directory.Exists(Path.GetDirectoryName(copyFilePath)) Then
                    System.IO.Directory.CreateDirectory(Path.GetDirectoryName(copyFilePath))
                End If
                Dim fs As System.IO.FileStream = New System.IO.FileStream(copyFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write)

                Dim buffer(1024 * 10) As Byte
                Do
                    Dim recvLength As Integer = resStream.Read(buffer, 0, buffer.Length)
                    If recvLength = 0 Then
                        Exit Do
                    End If
                    fs.Write(buffer, 0, recvLength)
                Loop
                fs.Flush()
                fs.Close()
            Catch ex As Exception
                Debug.WriteLine("DownloadError:" & ex.Message)
            End Try

            Try
                resStream.Close()
                res.Close()
                webreq.Abort()
            Catch ex As Exception
            End Try
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
            CFileLog.WriteLog("UPDATE-" & ex.Message, CFileLog.LEVEL_ERROR, CFileLog.EnumLogType.DOWNLOAD)
            Throw ex
        End Try
        CFileLog.WriteLog("UPDATE-END", CFileLog.LEVEL_NORMAL, CFileLog.EnumLogType.DOWNLOAD)

        Return True
    End Function



    ''' <summary>
    ''' 圧縮ファイルを展開 
    ''' </summary>
    ''' <param name="zipPath"></param>
    ''' <param name="extractDir"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function unZipFile(ByVal zipPath As String, ByVal extractDir As String) As String
        '展開するZIPファイルの設定
        'Dim zipPath As String = "C:\test.zip"
        '展開先のフォルダの設定
        'Dim extractDir As String = "C:\temp"

        'フォルダがない場合
        If Not System.IO.Directory.Exists(Path.GetDirectoryName(extractDir)) Then
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(extractDir))
        End If
        If Not System.IO.Directory.Exists(extractDir) Then
            System.IO.Directory.CreateDirectory(extractDir)
        End If
        Debug.WriteLine("extractDir:" & extractDir)

        Try
            '読み込む
            Dim fs As New System.IO.FileStream(zipPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)
            Dim zis As New ICSharpCode.SharpZipLib.Zip.ZipInputStream(fs)
            'パスワードが設定されているとき
            'zis.Password = "pass"

            'ZIP内のファイル情報を取得
            Dim ze As ICSharpCode.SharpZipLib.Zip.ZipEntry
            While True
                ze = zis.GetNextEntry()
                If ze Is Nothing Then
                    Exit While
                End If

                If Not ze.IsDirectory Then
                    'ファイル名
                    Dim fileName As String = System.IO.Path.GetFileName(ze.Name)
                    '展開先のフォルダ
                    Dim destDir As String = System.IO.Path.Combine(extractDir, System.IO.Path.GetDirectoryName(ze.Name))
                    System.IO.Directory.CreateDirectory(destDir)
                    Debug.WriteLine("destDir:" & (destDir))
                    '展開先のパス
                    Dim destPath As String = System.IO.Path.Combine(destDir, fileName)
                    '書込み
                    Dim writer As New System.IO.FileStream(destPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Write)

                    Dim buffer(2047) As Byte
                    Dim len As Integer
                    While True
                        len = zis.Read(buffer, 0, buffer.Length)
                        If len <= 0 Then
                            Exit While
                        End If
                        writer.Write(buffer, 0, len)
                    End While
                    '閉じる
                    writer.Close()
                End If
            End While

            zis.Close()
            fs.Close()

        Catch ex As Exception
            Debug.WriteLine("======展開NG" & vbNewLine & ex.Message)
            Return "NG"
        End Try
        Debug.WriteLine("======展開OK")
        Return "OK"

    End Function

    ''' <summary>
    '''     ファイルまたはディレクトリ、およびその内容を新しい場所にコピーします。
    '''     新しい場所に同名のファイルがある場合は上書きしません。
    ''' </summary>
    ''' <param name="stSourcePath">コピー元のディレクトリのパス。</param>
    ''' <param name="stDestPath">コピー先のディレクトリのパス。</param>
    ''' <remarks></remarks>
    Public Sub CopyDirectory(ByVal stSourcePath As String, ByVal stDestPath As String)
        CopyDirectory(stSourcePath, stDestPath, False)
    End Sub

    ''' <summary>
    '''     ファイルまたはディレクトリ、およびその内容を新しい場所にコピーします。
    ''' </summary>
    ''' <param name="stSourcePath">コピー元のディレクトリのパス。</param>
    ''' <param name="stDestPath">コピー先のディレクトリのパス。</param>
    ''' <param name="bOverwrite">コピー先が上書きできる場合は True。それ以外の場合は False。</param>
    ''' <remarks></remarks>
    Public Sub CopyDirectory(ByVal stSourcePath As String, ByVal stDestPath As String, ByVal bOverwrite As Boolean)
        ' コピー先のディレクトリがなければ作成する
        If System.IO.Directory.Exists(stDestPath) = False Then
            System.IO.Directory.CreateDirectory(stDestPath)
            'System.IO.File.SetAttributes(stDestPath, System.IO.File.GetAttributes(stSourcePath))
            bOverwrite = True
        End If

        ' コピー元のディレクトリにあるすべてのファイルをコピーする
        If bOverwrite Then
            For Each stCopyFrom As String In System.IO.Directory.GetFiles(stSourcePath)
                Dim stCopyTo As String = System.IO.Path.Combine(stDestPath, System.IO.Path.GetFileName(stCopyFrom))
                System.IO.File.Copy(stCopyFrom, stCopyTo, True)
            Next stCopyFrom

            ' 上書き不可能な場合は存在しない時のみコピーする
        Else
            For Each stCopyFrom As String In System.IO.Directory.GetFiles(stSourcePath)
                Dim stCopyTo As String = System.IO.Path.Combine(stDestPath, System.IO.Path.GetFileName(stCopyFrom))

                If System.IO.File.Exists(stCopyTo) = False Then
                    System.IO.File.Copy(stCopyFrom, stCopyTo, False)
                End If
            Next stCopyFrom
        End If

        ' コピー元のディレクトリをすべてコピーする (再帰)
        For Each stCopyFrom As String In System.IO.Directory.GetDirectories(stSourcePath)
            Dim stCopyTo As String = System.IO.Path.Combine(stDestPath, System.IO.Path.GetFileName(stCopyFrom))
            CopyDirectory(stCopyFrom, stCopyTo, bOverwrite)
        Next stCopyFrom
    End Sub

End Module
